package com.GlobalPaint.app.ui.HTML;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.codeBean;
import com.GlobalPaint.app.bean.postWZBean;
import com.GlobalPaint.app.bean.putWenBean;
import com.GlobalPaint.app.bean.putWenzhangBean;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.RichTextEditor;
import com.GlobalPaint.app.utils.RichTextEditor.EditData;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PutWenzhangActivity extends FragmentActivity {
    private static final int REQUEST_CODE_PICK_IMAGE = 1023;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1022;
    @BindView(R.id.tv_bt)
    EditText tvBt;
    @BindView(R.id.tv_ms)
    EditText tvMs;
    private RichTextEditor editor;
    private View btn1, btn2, btn3;
    private View.OnClickListener btnListener;
    private putWenzhangBean Bean;
    File file;
    private List<String> list;
    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private File mCurrentPhotoFile;// 照相机拍照得到的图片
    private TextView tvFresh;
    private ImageView iv_goback;
    codeBean bean;
    putWenBean putwenBean;
private String id;
    private TextView tv_common_center;
    private postWZBean postwzBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_put_tuji);
        ButterKnife.bind(this);
        id=getIntent().getStringExtra("id");
        tvFresh = (TextView) findViewById(R.id.tv_fresh);
        tv_common_center = (TextView) findViewById(R.id.tv_common_center);
        iv_goback = (ImageView) findViewById(R.id.iv_goback);
        iv_goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_common_center.setText("文章发布");
        tvFresh.setText("发送文章");
        tvFresh.setVisibility(View.VISIBLE);
        editor = (RichTextEditor) findViewById(R.id.richEditor);
        btnListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.hideKeyBoard();
                if (v.getId() == btn1.getId()) {
                    // 打开系统相册
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");// 相片类型
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                } else if (v.getId() == btn2.getId()) {
                    // 打开相机
                    openCamera();
                } else if (v.getId() == tvFresh.getId()) {
                    List<EditData> editList = editor.buildEditData();
                    // 下面的代码可以上传、或者保存，请自行实现
                    dealEditData(editList);
                }
            }
        };

        btn1 = findViewById(R.id.button1);
        btn2 = findViewById(R.id.button2);
        btn3 = findViewById(R.id.button3);

        btn1.setOnClickListener(btnListener);
        btn2.setOnClickListener(btnListener);
        btn3.setOnClickListener(btnListener);
        tvFresh.setOnClickListener(btnListener);
    }

    private void putTuji(File file, final String uri, final String biaoshi) {

        String url = Constants.JASON_SERVICE_URL + "info/saveInfoImages";
        DataManager.getInst().postHttpRequesFileClass(url, DataManager.userEntity.getCookie(), file, putWenzhangBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                Bean = (putWenzhangBean) o;
                if (Bean.getStatus() == 1) {
                    if (Bean.getData().length() > 0) {
                        String img = Bean.getData();
                        if (biaoshi.equals("REQUEST_CODE_PICK_IMAGE")) {
                            insertBitmap(getRealFilePath(Uri.parse(uri)), img);
                        } else {
                            insertBitmap(mCurrentPhotoFile.getAbsolutePath(), img);
                        }

                    }

                }

            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {

            }
        });
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    protected void dealEditData(List<EditData> editList) {
        String text = null;
        String img = null;
        if (editList.size() > 0) {
            list = new ArrayList<>();
            for (int i = 0; i < editList.size(); i++) {
                if (editList.get(i).inputStr != null) {
                    text = "<p>" + editList.get(i).inputStr + "</p></br>";
                    list.add(text);
                }
                if (editList.get(i).imagedata != null) {
                    img = "<img src="+ '"'+editList.get(i).imagedata +'"'+"style="+'"'+"max-width=650 max_height=650"+'"'+">";
                    list.add(img);
                }
                // list.add(text+img.replace("null",""));
            }
            String zong = "";
            String zong1 = "";
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    zong += list.get(i);
                }
                zong1 = "<div>" + zong + "</div>";
                Log.d("RichEditor", "commit inputStr=" + zong1);
                String bt=tvBt.getText().toString();
                String ms=tvMs.getText().toString();
                if(TextUtils.isEmpty(bt)){
                    Toast.makeText(PutWenzhangActivity.this,"请输入标题",Toast.LENGTH_LONG).show();
                    return;
                }
                if(TextUtils.isEmpty(ms)){
                    Toast.makeText(PutWenzhangActivity.this,"请输入图片描述",Toast.LENGTH_LONG).show();
                    return;
                }
                postwzBean=new postWZBean();
                postwzBean.setfCreatorId(DataManager.userEntity.getUserId());
                postwzBean.setfAuthor(DataManager.userEntity.getfNickName());
                postwzBean.setfNodeId(id);
                postwzBean.setfTitle(bt);
                postwzBean.setfMetaDescription(ms);
                postwzBean.setfValue(zong1);
                postWenzhang(DataManager.userEntity.getUserId(),DataManager.userEntity.getfNickName(),ms,
                        id,bt,zong1);

            }
        }

       /* for (EditData itemData : editList) {

        }*/
          /*  if (itemData.inputStr != null) {
                Log.d("RichEditor", "commit inputStr=" + itemData.inputStr);
            } else if (itemData.imagePath != null) {
                Log.d("RichEditor", "commit imgePath=" + itemData.imagePath);
                Log.d("RichEditor", "commit imagedata=" + itemData.imagedata);
            }
            String jian="<div>"+"<p>"+itemData.inputStr+"</p>"+"<p>"+itemData.imagedata+"</p>"+"</div>";
            Log.d("RichEditor", "commit imagedata=" + jian);
        }*/
    }

/*    private void postWenzhang(int userid,String name,String ms,String id,String bt,String zong1 ) {
        String url = Constants.JASON_SERVICE_URL + "info/saveInfoByPhone?fCreatorId="+userid
                +"&fAuthor="+name+"&fNodeId="+id+"&fTitle="+bt+"&fMetaDescription="+ms+"&fValue="+zong1;
        Log.d("postWenzhang", "postWenzhang: "+url);
            DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), codeBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                bean = (codeBean) o;
                if (bean.getStatus() == 1) {
                    finish();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(PutWenzhangActivity.this,"提交失败",Toast.LENGTH_LONG).show();
            }
        });
    }*/
    //2018-10-18 get改为post
private void postWenzhang(int userid,String name,String ms,String id,String bt,String zong1 ) {

    String url = Constants.JASON_SERVICE_URL + "info/saveInfoByPhone";

        DataManager.getInst().postHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), postwzBean, codeBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                bean = (codeBean) o;
                if (bean.getStatus() == 1) {
                    finish();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(PutWenzhangActivity.this,"提交失败",Toast.LENGTH_LONG).show();
            }
        });
}
    protected void openCamera() {
        try {
            // Launch camera to take photo for selected contact
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
            mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
        } catch (ActivityNotFoundException e) {
        }
    }

    public static Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 用当前时间给取得的图片命名
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat();
        return ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            // insertBitmap(getRealFilePath(uri));//在区域显示tu
            file = new File(getRealFilePath(uri));
            putTuji(file, uri.toString(), "REQUEST_CODE_PICK_IMAGE");
        } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
            //  insertBitmap(mCurrentPhotoFile.getAbsolutePath());
            file = new File(mCurrentPhotoFile.getAbsolutePath());
            putTuji(file, mCurrentPhotoFile.getAbsolutePath(), "REQUEST_CODE_CAPTURE_CAMEIA");
        }
    }

    /**
     * 添加图片到富文本剪辑器
     *
     * @param imagePath
     */
    private void insertBitmap(String imagePath, String imagedata) {
        editor.insertImage(imagePath, imagedata);
    }

    /**
     * 根据Uri获取图片文件的绝对路径
     */
    public String getRealFilePath(final Uri uri) {
        if (null == uri) {
            return null;
        }

        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (isShouldHideKeyboard(v, ev)) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        }
        return super.dispatchTouchEvent(ev);
        }

        // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
        private boolean isShouldHideKeyboard(View v, MotionEvent event) {
                if (v != null && (v instanceof EditText)) {
                int[] l = {0, 0};
                v.getLocationInWindow(l);
                int left = l[0],
                top = l[1],
                bottom = top + v.getHeight(),
                right = left + v.getWidth();
                return !(event.getX() > left && event.getX() < right
        && event.getY() > top && event.getY() < bottom);
                }
                return false;
                }
    public void hideSoftInput(View view){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()){
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
